package com.pn.taikao.service.impl;

import com.pn.taikao.entity.PaperQuestion;
import com.pn.taikao.mapper.PaperQuestionMapper;
import com.pn.taikao.service.PaperQuestionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class PaperQuestionServiceImpl implements PaperQuestionService {

    private final PaperQuestionMapper paperQuestionMapper;

    public PaperQuestionServiceImpl(PaperQuestionMapper paperQuestionMapper) {
        this.paperQuestionMapper = paperQuestionMapper;
    }

    @Override
    public void addQuestionToPaper(Long paperId, Long questionId, Double score) {
        PaperQuestion paperQuestion = new PaperQuestion();
        paperQuestion.setPaperId(paperId);
        paperQuestion.setQuestionId(questionId);
        paperQuestion.setScore(score);
        paperQuestion.setCreateTime(LocalDateTime.now());
        paperQuestion.setUpdateTime(LocalDateTime.now());
        paperQuestionMapper.insert(paperQuestion);
    }

    @Override
    public void removeQuestionFromPaper(Long paperId, Long questionId) {
        paperQuestionMapper.deleteByPaperIdAndQuestionId(paperId, questionId);
    }

    @Override
    @Transactional
    public void clearPaperQuestions(Long paperId) {
        paperQuestionMapper.deleteByPaperId(paperId);
    }

    @Override
    @Transactional
    public void setPaperQuestions(Long paperId, List<Long> questionIds, List<Double> scores) {
        // 先清空原有题目
        clearPaperQuestions(paperId);
        
        // 添加新题目
        for (int i = 0; i < questionIds.size(); i++) {
            Long questionId = questionIds.get(i);
            Double score = i < scores.size() ? scores.get(i) : 5.0; // 默认5分
            addQuestionToPaper(paperId, questionId, score);
        }
    }

    @Override
    public List<PaperQuestion> getByPaperId(Long paperId) {
        return paperQuestionMapper.selectByPaperId(paperId);
    }

    @Override
    public PaperQuestion getByPaperIdAndQuestionId(Long paperId, Long questionId) {
        return paperQuestionMapper.selectByPaperIdAndQuestionId(paperId, questionId);
    }

    @Override
    public List<Long> getQuestionIdsByPaperId(Long paperId) {
        return paperQuestionMapper.selectQuestionIdsByPaperId(paperId);
    }

    @Override
    public long countByPaperId(Long paperId) {
        return paperQuestionMapper.countByPaperId(paperId);
    }
}

